package core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import agent.AgentBoard;

import core.basic.Movement;
import core.basic.Piece;


class Board implements AgentBoard{
	private List<Piece> pieces;

	public Board(){
		pieces = new ArrayList<Piece>();
	}
	
	public boolean canPut(Piece p) {
		return 	pieces.isEmpty() || this.canPutLeft(p) || this.canPutRight(p);
	}
	
	public boolean canPutLeft(Piece p) {
		return 	size() == 0 ||
				p.getRight() == pieces.get(0).getLeft()
				||
				p.getLeft() == pieces.get(0).getLeft();
	}
	
	public boolean canPutRight(Piece p) {
		return 	size() == 0 ||
				p.getLeft() == pieces.get(pieces.size()-1).getRight()
				||
				p.getRight() == pieces.get(pieces.size()-1).getRight();
	}
	
	public void putPiece(Piece p, boolean side){
		if (pieces.isEmpty()) {
			pieces.add(p);
			return;
		}
		if (side == LEFT && this.canPutLeft(p)) {
			this.putPieceLeft(p);
			return;
		}
		if (this.canPutRight(p)) {
			this.putPieceRight(p);
			return;
		}
		//TODO retirar o alerta na conclus�o do programa
		if (!this.canPut(p)) {
			//h� algo errado, a pe�a n�o cabe
			System.err.println("h� algo errado, a pe�a n�o cabe");
			return;
		}			

	}

	private void putPieceLeft(Piece p) {
		if (pieces.get(0).getLeft() != p.getRight()) {
			p.invert();
		}
		pieces.add(0, p);// pe�a no inicio
	}

	private void putPieceRight(Piece p) {
		if (pieces.get(pieces.size()-1).getRight() != p.getLeft()) {
			p.invert();
		}
		pieces.add(p);//pe�a no fim
	}
	
	public Iterator<Piece> iterator(){
		return pieces.iterator();
	}
	public String toString() {
		String res = "";
		for (Piece p : pieces) {
			res += p.toString();
		}
		return res;
	}

	@Override
	public double size() {
		return pieces.size();
	}

	@Override
	public boolean canMake(Movement m) {
		if (m.pass)
			return true;
		if (m.side == LEFT)
			return canPutLeft(m.p);
		return canPutRight(m.p);
	}
}
